package com.zq.widget.inverted.game.role.equipment;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;

import com.zq.widget.inverted.game.role.impl.base.DrawableRole;
import com.zq.widget.inverted.game.role.equipment.weapon.Weapon;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by zhangqiang on 2018/3/30.
 */
public class EquipmentRole extends DrawableRole {

    private List<Equipment> equipments = new ArrayList<>();
    private List<Integer> takeEffectTypes = new ArrayList<>();

    public EquipmentRole(Context context, int drawableResId) {
        super(context, drawableResId);
    }

    @Override
    public void preDraw() {
        super.preDraw();

        takeEffectTypes.clear();
        Iterator<Equipment> iterator = equipments.iterator();
        while (iterator.hasNext()){

            Equipment equipment = iterator.next();
            if(!equipment.isValid()){
                iterator.remove();
                equipment.onDrop();
                continue;
            }
            int type = equipment.type();
            if(takeEffectTypes.contains(type)){
                continue;
            }
            takeEffectTypes.add(type);
            equipment.compute();
        }
    }

    public void addEquipment(Equipment equipment){

        equipments.add(equipment);
        Collections.sort(equipments, new Comparator<Equipment>() {
            @Override
            public int compare(Equipment o1, Equipment o2) {

                if(o1.priority() > o2.priority()){
                    return 1;
                }else if(o1.priority() < o2.priority()){
                    return -1;
                }
                return 0;
            }
        });
    }

    public void drop(Equipment equipment){

        boolean remove = equipments.remove(equipment);
        if(remove){
            equipment.onDrop();
        }
    }

    @Nullable
    public Equipment findEquipment(int type){

        for (Equipment equipment : equipments) {

            if(equipment.type() == type){
                return equipment;
            }
        }
        return null;
    }
}
